<template>
  <commonDrawer
    :title="drawerName"
    :drawer="drawerShow"
    :size="500"
    :isShowMoreBtn="true"
    @closeDraw="closeDraw"
    @cancelFun="closeDraw"
    @save="save"
  >
    <template slot="column">
      <div v-if="formData.status === 3" class="no-pass">
        <p><i class="el-icon-error"></i>未通过原因:</p>
        <p class="cont">
          {{ this.formData.reason }}
        </p>
      </div>
      <el-form
        ref="form"
        :model="formData"
        label-position="top"
        :rules="rules"
        size="small"
      >
        <el-form-item label="模板名称" prop="displayName">
          <el-input
            :maxlength="30"
            placeholder="请输入"
            show-word-limit
            clearable
            v-model="formData.displayName"
          ></el-input>
        </el-form-item>
        <el-form-item label="短信类型" prop="smsType">
          <el-radio-group v-model="formData.smsType">
            <el-radio label="validateCode"> 验证码 </el-radio>
            <el-radio label="notice"> 通知短信 </el-radio>
            <el-radio label="marketing"> 营销短信 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="content">
          <span slot="label">
            <span>模板内容</span>
            <!-- <el-dropdown
              trigger="hover"
              @command="handleCommand"
              style="float: right"
            >
              <span class="variable"
                >系统变量<i class="el-icon-arrow-down"></i
              ></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="item in variableList"
                  :key="item.key"
                  :command="item"
                >
                  {{ item.variableName }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
          </span>
          <el-input
            type="textarea"
            :rows="4"
            id="textarea"
            placeholder="验证码为：${code}, 该验证码5分钟内有效，请勿泄露与他人"
            v-model="formData.content"
          ></el-input>
        </el-form-item>
        <p class="warn"><i class="el-icon-warning"></i>小贴士</p>
        <p class="tip-cont">
          1.短信字数包含签名+模板内容+变量内容，短信 70 个字数含以内，按 1
          条短信计费；超出 67 个字为长短信，按照 67 个字数记为 1
          条短信费用。汉字、字母、数字、符号（不区分全角和半角），都按照一个字计算；<br />
          2.固定格式如：${name}、${code}等，中间字母应代表变量名称。首字母必须为英文字母，只支持字母、数字和下划线组成，不支持全数字，同时不支持设置为email、mobile、id、nick、site等；<br />
          3.变量值限制为1～35个字符；验证码模板，变量限制为1～20个字符；
          4.公众号、小程序、App、链接、IP等内容需置于变量外。若链接无法固定，建议格式为：一级域名+变量，如www.xxxx.com${code}；<br />
          5.为避免与签名混淆，在模板内容任意位置均不能使用【】，在模板内容首尾不能使用[]。不支持特殊符号例如#『』「」〖〗
          m² • ①★※→等；
        </p>
        <el-form-item label="场景说明" prop="sceneDescription">
          <el-input
            type="textarea"
            :rows="6"
            maxlength="200"
            show-word-limit
            placeholder="场景说明是签名审核的参考信息之一，请详细描达己上线业务的使用场景，并提供可以验证这些业务的网站链接、已备案域名地址、应用市场下载链接、公众号或小程序全称等信息。对于登录场景，还需提供测试账号密码。信息完善的申请说明会提高签名、模板的审核效率。"
            v-model="formData.sceneDescription"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import Upload from '@/components/globalTool/upload/index.vue'
import { commonAction } from '@/utils/common'
import commonDrawer from '@/components/globalTool/resizeDrawer/drawer.vue'
import { CommonModule } from '@/store/modules/common'
import { v4 as uuidv4 } from 'uuid'
@Component({
  name: 'addOrEditAutograph',
  components: {
    Upload,
    commonDrawer
  }
})
export default class CustomerTemplateSetting extends Vue {
  [x: string]: any
  private variableList: any = [
    {
      variableName: '客户名称',
      key: 'customerName'
    }
  ]

  private type: any = ''

  private drawerName: any = ''

  private drawerShow: boolean = false

  public formData: any = {
    displayName: '',
    smsType: 'validateCode',
    content: '',
    sceneDescription: '',
    status: 1 // 1待审核 2审核通过 3审核不通过
  }

  private rules: any = {
    displayName: [{ required: true, validator: this.validateName, trigger: 'blur' }],
    smsType: [{ required: true, message: '请选择短信类型', trigger: 'change' }],
    content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }],
    sceneDescription: [{ required: true, message: '请输入场景说明', trigger: 'blur' }]
  }

  get getAccountId () {
    return (CommonModule as any).session.user.accountId || ''
  }

  get getCurAgent () {
    return (CommonModule as any).session.user._id || ''
  }

  private validateName (rule, value, callback) {
    if (value.length < 2 || /^\s*$/g.test(value)) {
      callback(new Error('模板名称不能为空且最小长度为2'))
    } else {
      callback()
    }
  }

  private getUUID () {
    return uuidv4().replace(/-/g, '')
  }

  private async handleCommand (val: any) {
    if (this.formData.content.indexOf('${' + val.key + '}') > -1) {
      return this.$message.error('一个变量只能使用一次')
    }
    const myField: any = document.querySelector('#textarea')
    if (myField.selectionStart || myField.selectionStart === 0) {
      const startPos = myField.selectionStart
      const endPos = myField.selectionEnd
      this.formData.content = myField.value.substring(0, startPos) + '${' + val.key + '}' + myField.value.substring(endPos, myField.value.length)
      await this.$nextTick()
      myField.focus()
    } else {
      this.formData.content = '${' + val.key + '}'
    }
  }

  public openDrawer (type: any) {
    this.type = type
    this.drawerShow = true
    this.drawerName = type === 'add' ? '创建模板' : '编辑模板'
  }

  public clearData () {
    this.formData = {
      displayName: '',
      smsType: 'validateCode',
      content: '',
      sceneDescription: '',
      status: 1 // 1待审核 2审核通过 3审核不通过
    }
  }

  private matchVariable (str: any) {
    const repValArr: any = []
    str.replace(/\{(.*?)\}/g, (val, repVal) => {
      if (!repValArr.find(item => item === repVal)) {
        repValArr.push(repVal)
      }
    })
    return repValArr.join(',')
  }

  private save () {
    (this.$refs as any).form.validate(valid => {
      if (valid) {
        const { displayName, smsType, content, sceneDescription, id } = this.formData
        const params = this.matchVariable(this.formData.content) // 模板内容中是否有系统变量
        const sendData = {
          requestId: this.getUUID(),
          action: 'MANAGER_TEMPLATE_MODIFY',
          param: {
            id,
            displayName,
            smsType,
            content,
            sceneDescription,
            status: 1,
            customer: this.getAccountId,
            type: params ? 2 : 1, // 2有参模板、1无参模板
            params,
            operator: this.getCurAgent
          }
        }
        const actionData = {
          url: '/sms-api/sms/manager/template/data',
          method: 'POST',
          data: this.type === 'add' ? sendData : sendData
        }
        commonAction(actionData).then(res => {
          if (res.code === '0000200') {
            this.$message.success(`${this.type === 'add' ? '创建' : '更新'}成功`)
            this.drawerShow = false
            this.$emit('updateTempletList')
          }
        })
      }
    })
  }

  private closeDraw () {
    this.drawerShow = false
  }
}
</script>
<style lang="stylus" scoped>
.el-form--label-top
  >>>.el-form-item__label
    display inline
.variable
  color $c-mian
  cursor pointer
  background #E5F3FD
  border-radius 4px
  padding 6px 10px
  color #008BEE
  i
    color #008BEE
    margin-left 6px
    font-size 12px
.warn
  margin-bottom 4px
  font-weight 600
  color #303753
  i
    color #008BEE
    font-size 14px
    margin-right 6px
.tip-cont
  color #767E91
  line-height 20px
  margin 0 0 10px 8px
.no-pass
  padding 12px 18px 12px 12px
  background #FFFBE6
  border-radius 4px
  color #303753
  font-weight 600
  font-family PingFang SC
  .cont
    margin-left 20px
  i
    margin-right 6px
    font-size 14px
    color #FAAD14
</style>
